<?php
namespace Game\Controller;
use Common\Controller\AdminbaseController;
use Library\GameTable;
class PlaybillController extends AdminbaseController {
	protected $game_machine_model,$game_playbill_model,$game_playbill_machine_model,$game_desktop_model,$region_model,$users_model;
	function _initialize() {
		parent::_initialize();
		$this->game_machine_model = D("GameMachine");
		$this->game_playbill_model = D("GamePlaybill");
		$this->game_playbill_machine_model = D("GamePlaybillMachine");
		$this->game_desktop_model = D("GameDesktop");
		$this->region_model = D("Region");
		$this->users_model = D("Users");
	}

    private function playbillstatus() {
		$playbillstatus =
			array(
	            array('id' => '0', 'name'=>'请选择'),
	            array('id' => '1', 'name'=>'未启用'),
	            array('id' => '2', 'name'=>'已启用'),
	            array('id' => '3', 'name'=>'已停用'),
		);
		return $playbillstatus;
    }
    function index(){
        if(I('param.start_time')){
                $search[] = array('start_at'=>array('egt',I('param.start_time')));
        }
        if(I('param.end_time')){
                $search[] = array('end_at'=>array('elt',I('param.end_time')));
        }
        if(I('param.template')){
                $search[] = array('template_id'=>I('param.template'));
        }
        if(I('param.pstatus')){
                $search[] = array('pstatus'=>I('param.pstatus'));
        }
		$_GET['start_time'] =I('param.start_time');
		$_GET['end_time'] =I('param.end_time');
		$_GET['template'] =I('param.template');
		$_GET['pstatus'] =I('param.pstatus');
		$playbill = $this->playbillstatus();
		$count=$this->game_playbill_model
		->where($search)
		->count();
		$page = $this->page($count, 50);
		$game = $this->game_playbill_model
		->where($search)
		->limit($page->firstRow . ',' . $page->listRows)
		->order("id DESC")
		->select();
		if($game){
			foreach($game as $guser){
				$uid[] =$guser['userid'];
			}
			$users=$this->users_model->field("id,user_login")->where(array('id'=>array('in',$uid)))->select();
			$this->assign("users", $users);
		}
		$this->assign("status", $playbill);
		$template = GameTable::getProgramTemplateList();
		if(!is_array($template)){
			$template = array(array('id' => '0', 'name'=>'获取失败'));
		}
		$this->assign("template", $template);
		$this->assign("game", $game);
		$this->assign("page", $page->show('Admin'));
		$this->assign("count",$count);
		$this->display();
	}
	public function customize(){
		$datetime = date("Y-m-d H:i:s");
		$where =array('pstatus'=>2,array('start_at'=>array('elt',$datetime),'_logic'=>"OR",'end_at'=>array('egt',$datetime)));
		$game = $this->game_playbill_model
		->where($where)
		->order("id DESC")
		->select();
		$this->assign("game",$game);
		$this->display();
    }
	public function customize_post(){
		if(IS_POST){
			$area_sn = explode(',',I("post.area_sn"));
			$pid = explode(',',I("post.pid"));
			$pid = $pid[0];
			$playbill = $this->game_playbill_model->where(array('id'=>$pid))->find();
			if($playbill){
				$playbill_machine = $this->game_playbill_machine_model->where(array('pid'=>$pid))->group('aid')->select();
				$playProgram['id'] = $playbill['template_id'];
				$playProgram['name'] = $playbill['name'];
				$playProgram['width'] = $playbill['template_width'];
				$playProgram['height'] = $playbill['template_height'];
				$playProgram['controlWidth'] = $playbill['template_width'];
				$playProgram['controlHeight'] = $playbill['template_height'];
				$playProgram['time'] = strtotime($playbill['end_at']) - strtotime($playbill['start_at']);
				foreach($playbill_machine as $pm){
					$areas = NULL;
					$areas['areaIndex'] = $pm['aid'];
					$areas['lockState'] = $playbill['ptype'];
					$areas['height'] = $pm['aheight'];
					$areas['left'] = $pm['aleft'];
					$areas['name'] = $pm['aname'];
					$areas['top'] = $pm['atop'];
	//					$areas['type'] = $pm['atype'];
					$areas['width'] = $pm['awidth'];
					$machines = $this->game_playbill_machine_model->where(array('pid'=>$pid,'aid'=>$pm['aid']))->select();
					foreach($machines as $k=>$mid){
						$sources = $rjson = NULL;
	    				$desktop = $this->game_desktop_model->where(array('id'=>$mid['mid']))->find();
	    				$rjson = json_decode($desktop['return_json'], true);
						$sources =$rjson[0];
						$areas['type'] = $sources['type'];
						$sources['sort'] =$k+1;
						$sources['playTimes'] =$mid['weights'];
						$sources['interval'] =$mid['mtime'];
						$areas['sources'][] = $sources;
					}
					$playProgram['areas'][] = $areas;
				}

					$tmlsns = GameTable::getTerminalsByTmlSNs($area_sn);
					if(is_array($tmlsns)){
						foreach($tmlsns as $tmlsn){
							$tmls[] = $tmlsn['id'];
						}
						$result = GameTable::addPlanForProgramTemplate($playbill['template_id'],$tmls,$playProgram);
					}
				if(is_string($tmlsns)){
					$this->error($tmlsns);
				} else {
					$this->success($result['result_desc'],U('Playbill/index'));
				}
			}
		}
    }
	function add(){
		$template = GameTable::getProgramTemplateList();
		if(!is_array($template)){
			$template = array(array('id' => '0', 'name'=>'获取失败'));
		}
		$this->assign("template", $template);
		$province = $this->region_model->where(array('level'=>1))->select();
		$city = $this->region_model->where(array('level'=>2))->select();
		$this->assign("province", $province);
		$this->assign("city", $city);
		$this->display();
	}


	function material(){
		if(!I("post.name")){
			$this->error("请填写节目单名称！");
		}
		if(!I("post.template")){
			$this->error("请选择节目单模板！");
		}
		if(I("post.source") == 'add'){
			$datetime = date("Y-m-d H:i:s");
			$where =array('dstatus'=>2,array('start_at'=>array('elt',$datetime),'_logic'=>"OR",'end_at'=>array('egt',$datetime)));
		}
		if(I("post.source") == 'edit'){
			$where =array('dstatus'=>2);
			$machines = $this->game_playbill_machine_model->where(array('pid'=>I("post.id")))->select();
        	$this->assign('machine', $machines);
		}
		$templates = explode(',',I("post.template"));
		$template = $templates[0];
		$template_id = GameTable::getProgramTemplateById($template);
		$this->assign("template_id", $template_id['areas']);
        $desktop = $this->game_desktop_model
        ->where($where)
        ->select();
        $this->assign('desktop', $desktop);
		$this->display();
	}
	function add_post(){
		if (IS_POST) {
			if(I("post.ptype") == 2){
				if($this->game_playbill_model->where(array('ptype'=>I("post.ptype")))->find()){
					$this->error("底层节目单已存在！");
				}
			}
			$template = explode(',',I("post.template"));
			$_POST['pstatus'] = 1;
			$_POST['template_id'] = $template[0];
			$_POST['template_name'] = $template[1];
			$_POST['template_preview'] = $template[2];
			$_POST['template_height'] = $template[3];
			$_POST['template_width'] = $template[4];
			$_POST['create_user'] = get_current_admin_id();
			$_POST['userid'] = get_current_admin_id();
			$pid = $this->game_playbill_model->add($_POST);
			if($pid){
				$ptimes = I("post.ptimes");
				$pweights = I("post.pweights");
				$areas = I("post.areas");
				foreach(I("post.dids") as$p=> $dids){
					foreach($dids as$d=>$did){
						$machine['pid'] = $pid;
						$machine['aid'] = $p;
						$machine['mid'] = $did;
						$machine['mtime']= $ptimes[$p][$d];
						$machine['awidth']= $areas[$p]['awidth'];
						$machine['weights']= $pweights[$p][$d];
						$machine['aheight']= $areas[$p]['aheight'];
						$machine['aleft']= $areas[$p]['aleft'];
						$machine['aname']= $areas[$p]['aname'];
						$machine['atop']= $areas[$p]['atop'];
						$machine['atype']= $areas[$p]['atype'];
						$this->game_playbill_machine_model->add($machine);
					}
				}
				$this->success("添加成功！",U('Playbill/index'));
			} else {
				$this->error("添加失败！");
			}
		}
	}
	function edit(){
		$game = $this->game_playbill_model->where(array('id'=>I("get.id")))->find();
		if($game['area_id']){
			$areanames_model = $this->region_model->where(array('code'=>array('in',$game['area_id'])))->select();
			foreach($areanames_model as$k=>$area){
				$areanames[$k] =$area['shortname'];
			}
			$this->assign("areacode", $game['area_id']);
			$this->assign("areanames", $areanames);
		}
		$province = $this->region_model->where(array('level'=>1))->select();
		$city = $this->region_model->where(array('level'=>2))->select();
		$this->assign("province", $province);
		$this->assign("city", $city);
		$this->assign("game", $game);
		$this->display();
	}
	function edit_post(){
		if (IS_POST) {
			$_POST['userid'] = get_current_admin_id();
			$pid =	I("post.pid");
			if($pid){
				$this->game_playbill_model->where(array('id'=>$pid))->save($_POST);
				$this->game_playbill_machine_model->where(array('pid'=>$pid))->delete();
				$ptimes = I("post.ptimes");
				$pweights = I("post.pweights");
				$areas = I("post.areas");
				foreach(I("post.dids") as$p=> $dids){
					foreach($dids as$d=>$did){
						$machine['pid'] = $pid;
						$machine['aid'] = $p;
						$machine['mid'] = $did;
						$machine['mtime']= $ptimes[$p][$d];
						$machine['weights']= $pweights[$p][$d];
						$machine['awidth']= $areas[$p]['awidth'];
						$machine['aheight']= $areas[$p]['aheight'];
						$machine['aleft']= $areas[$p]['aleft'];
						$machine['aname']= $areas[$p]['aname'];
						$machine['atop']= $areas[$p]['atop'];
						$machine['atype']= $areas[$p]['atype'];
						$this->game_playbill_machine_model->add($machine);
					}
				}
				$this->success("修改成功！",U('Playbill/index'));
			} else {
				$this->error("修改失败！");
			}
		}
	}
	public function pull(){
    	if (I("get.id")) {
    		$playbill = $this->game_playbill_model->where(array('id'=>I("get.id")))->find();
    		if ($playbill) {
				$playbill_machine = $this->game_playbill_machine_model->where(array('pid'=>I("get.id")))->group('aid')->select();
				$playProgram['id'] = $playbill['template_id'];
				$playProgram['name'] = $playbill['name'];
				$playProgram['width'] = $playbill['template_width'];
				$playProgram['height'] = $playbill['template_height'];
				$playProgram['controlWidth'] = $playbill['template_width'];
				$playProgram['controlHeight'] = $playbill['template_height'];
				$playProgram['time'] = strtotime($playbill['end_at']) - strtotime($playbill['start_at']);
				foreach($playbill_machine as $pm){
					$areas = NULL;
					$areas['areaIndex'] = $pm['aid'];
					$areas['lockState'] = $playbill['ptype'];
					$areas['height'] = $pm['aheight'];
					$areas['left'] = $pm['aleft'];
					$areas['name'] = $pm['aname'];
					$areas['top'] = $pm['atop'];
//					$areas['type'] = $pm['atype'];
					$areas['width'] = $pm['awidth'];
					$machines = $this->game_playbill_machine_model->where(array('pid'=>I("get.id"),'aid'=>$pm['aid']))->select();
					foreach($machines as $k=>$mid){
						$sources = $rjson = NULL;
        				$desktop = $this->game_desktop_model->where(array('id'=>$mid['mid']))->find();
        				$rjson = json_decode($desktop['return_json'], true);
						$sources =$rjson[0];
						$areas['type'] = $sources['type'];
						$sources['sort'] =$k+1;
						$sources['playTimes'] =$mid['weights'];
						$sources['interval'] =$mid['mtime'];
						$areas['sources'][] = $sources;
					}
					$playProgram['areas'][] = $areas;
				}
				if($playbill['area_id'] != '100000'){

					$search[] =array(array('province_id'=>array('in',$playbill['area_id'])),
									'_logic'=>"OR",
									array('city_id'=>array('in',$playbill['area_id'])),
									'_logic'=>"OR",
									array('district_id'=>array('in',$playbill['area_id'])),
									);
				}
				$tmlids = $this->game_machine_model->where($search)->select();
				foreach($tmlids as $tmlid){
					$tmls[] = $tmlid['tmlid'];
				}
					$result = GameTable::addPlanForProgramTemplate($playbill['template_id'],$tmls,$playProgram);
				if(is_string($result)){
    				$this->error($result);
				}else{
    				$this->error($result['result_desc']);
				}
    		} else {
    			$this->error('节目单下发失败！');
    		}
    	} else {
			$this->error($this->game_playbill_model->getError());
    	}
    }
	public function up(){
    	if (I("get.id")) {
    		if ($this->game_playbill_model->where(array('id'=>I("get.id")))->setField('pstatus','2')) {
    			$this->success("节目单启用成功！");
    		} else {
    			$this->error('素材启用失败！');
    		}
    	} else {
			$this->error($this->game_playbill_model->getError());
    	}
    }

    public function down(){
    	if (I("get.id")) {
    		if ($this->game_playbill_model->where(array('id'=>I("get.id")))->setField('pstatus','3')) {
    			$this->success("素材停用成功！");
    		} else {
    			$this->error('素材停用失败！');
    		}
    	} else {
			$this->error($this->game_playbill_model->getError());
    	}
    }
}
